<template>
  <AdminLayout>
    <template #header>
      <div class="flex items-center justify-between">
        <h2 class="text-xl font-semibold text-gray-900">队列管理</h2>
        <div class="flex space-x-2">
          <button
            @click="refreshData"
            :disabled="loading"
            class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
          >
            <svg class="w-4 h-4 mr-2" :class="{ 'animate-spin': loading }" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            刷新
          </button>
          <button
            @click="showClearModal = true"
            class="inline-flex items-center px-3 py-2 border border-red-300 shadow-sm text-sm leading-4 font-medium rounded-md text-red-700 bg-white hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
          >
            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
            清空队列
          </button>
        </div>
      </div>
    </template>

    <!-- 队列统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <div class="bg-white overflow-hidden shadow rounded-lg">
        <div class="p-5">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <svg class="h-6 w-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
              </svg>
            </div>
            <div class="ml-5 w-0 flex-1">
              <dl>
                <dt class="text-sm font-medium text-gray-500 truncate">待处理任务</dt>
                <dd class="text-lg font-medium text-gray-900">{{ props.stats.pending_jobs }}</dd>
              </dl>
            </div>
          </div>
        </div>
      </div>

      <div class="bg-white overflow-hidden shadow rounded-lg">
        <div class="p-5">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <svg class="h-6 w-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
            </div>
            <div class="ml-5 w-0 flex-1">
              <dl>
                <dt class="text-sm font-medium text-gray-500 truncate">失败任务</dt>
                <dd class="text-lg font-medium text-gray-900">{{ props.stats.failed_jobs }}</dd>
              </dl>
            </div>
          </div>
        </div>
      </div>

      <div class="bg-white overflow-hidden shadow rounded-lg">
        <div class="p-5">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <svg class="h-6 w-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <div class="ml-5 w-0 flex-1">
              <dl>
                <dt class="text-sm font-medium text-gray-500 truncate">已处理任务</dt>
                <dd class="text-lg font-medium text-gray-900">{{ props.stats.processed_jobs }}</dd>
              </dl>
            </div>
          </div>
        </div>
      </div>

      <div class="bg-white overflow-hidden shadow rounded-lg">
        <div class="p-5">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <svg class="h-6 w-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
              </svg>
            </div>
            <div class="ml-5 w-0 flex-1">
              <dl>
                <dt class="text-sm font-medium text-gray-500 truncate">队列连接</dt>
                <dd class="text-lg font-medium text-gray-900">{{ props.stats.connection }}</dd>
              </dl>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 队列健康状态 -->
    <div class="mb-8">
      <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
          <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">队列健康状态</h3>
          <div class="flex items-center mb-4">
            <div class="flex-shrink-0">
              <div 
                class="h-3 w-3 rounded-full"
                :class="{
                  'bg-green-400': props.queueHealth.status === 'healthy',
                  'bg-yellow-400': props.queueHealth.status === 'warning',
                  'bg-red-400': props.queueHealth.status === 'error'
                }"
              ></div>
            </div>
            <div class="ml-3">
              <p class="text-sm font-medium text-gray-900">
                {{ props.queueHealth.status === 'healthy' ? '健康' : props.queueHealth.status === 'warning' ? '警告' : '错误' }}
              </p>
            </div>
          </div>
          
          <div v-if="props.queueHealth.issues && props.queueHealth.issues.length > 0" class="mb-4">
            <h4 class="text-sm font-medium text-red-600 mb-2">问题:</h4>
            <ul class="list-disc list-inside text-sm text-red-600">
              <li v-for="issue in props.queueHealth.issues" :key="issue">{{ issue }}</li>
            </ul>
          </div>
          
          <div v-if="props.queueHealth.recommendations && props.queueHealth.recommendations.length > 0">
            <h4 class="text-sm font-medium text-blue-600 mb-2">建议:</h4>
            <ul class="list-disc list-inside text-sm text-blue-600">
              <li v-for="recommendation in props.queueHealth.recommendations" :key="recommendation">{{ recommendation }}</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- 最近任务和失败任务 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
      <!-- 最近任务 -->
      <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
          <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">最近任务</h3>
          <div v-if="!props.recentJobs || props.recentJobs.length === 0" class="text-center py-4 text-gray-500">
            暂无任务
          </div>
          <div v-else class="space-y-3">
            <div 
              v-for="job in props.recentJobs" 
              :key="job.id"
              class="border border-gray-200 rounded-lg p-3"
            >
              <div class="flex items-center justify-between">
                <div>
                  <p class="text-sm font-medium text-gray-900">{{ job.job }}</p>
                  <p class="text-xs text-gray-500">队列: {{ job.queue }}</p>
                </div>
                <div class="text-right">
                  <p class="text-xs text-gray-500">尝试次数: {{ job.attempts }}</p>
                  <p class="text-xs text-gray-500">{{ formatDate(job.created_at) }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 失败任务 -->
      <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg leading-6 font-medium text-gray-900">失败任务</h3>
            <button
              v-if="props.failedJobs && props.failedJobs.length > 0"
              @click="retryAllFailedJobs"
              :disabled="loading"
              class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
            >
              重试全部
            </button>
          </div>
          
          <div v-if="!props.failedJobs || props.failedJobs.length === 0" class="text-center py-4 text-gray-500">
            暂无失败任务
          </div>
          <div v-else class="space-y-3">
            <div 
              v-for="job in props.failedJobs" 
              :key="job.id"
              class="border border-red-200 rounded-lg p-3"
            >
              <div class="flex items-start justify-between">
                <div class="flex-1">
                  <p class="text-sm font-medium text-gray-900">{{ job.job }}</p>
                  <p class="text-xs text-gray-500">队列: {{ job.queue }}</p>
                  <p class="text-xs text-red-600 mt-1">{{ job.exception }}</p>
                </div>
                <div class="flex space-x-2 ml-4">
                  <button
                    @click="retryFailedJob(job.id)"
                    :disabled="loading"
                    class="inline-flex items-center px-2 py-1 border border-transparent text-xs leading-4 font-medium rounded text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
                  >
                    重试
                  </button>
                  <button
                    @click="deleteFailedJob(job.id)"
                    :disabled="loading"
                    class="inline-flex items-center px-2 py-1 border border-transparent text-xs leading-4 font-medium rounded text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 disabled:opacity-50"
                  >
                    删除
                  </button>
                </div>
              </div>
              <p class="text-xs text-gray-500 mt-2">{{ formatDate(job.failed_at) }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 清空队列确认模态框 -->
    <Modal v-if="showClearModal" @close="showClearModal = false">
      <div class="p-6">
        <h3 class="text-lg font-medium text-gray-900 mb-4">确认清空队列</h3>
        <p class="text-sm text-gray-500 mb-6">
          此操作将清空所有待处理的任务，无法撤销。确定要继续吗？
        </p>
        <div class="flex justify-end space-x-3">
          <button
            @click="showClearModal = false"
            class="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          >
            取消
          </button>
          <button
            @click="clearQueue"
            :disabled="loading"
            class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 disabled:opacity-50"
          >
            确认清空
          </button>
        </div>
      </div>
    </Modal>
  </AdminLayout>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { router, usePage } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import Modal from '@/Components/Modal.vue'
import { useNotification } from '@/composables/useNotification'

// 定义 props - 符合 Inertia.js 最佳实践
const props = defineProps({
  stats: {
    type: Object,
    default: () => ({
      connection: 'sync',
      pending_jobs: 0,
      failed_jobs: 0,
      processed_jobs: 0,
      queue_size: 0
    })
  },
  recentJobs: {
    type: Array,
    default: () => []
  },
  failedJobs: {
    type: Array,
    default: () => []
  },
  queueHealth: {
    type: Object,
    default: () => ({
      status: 'healthy',
      issues: [],
      recommendations: []
    })
  }
})

const { showNotification } = useNotification()
const page = usePage()

// 响应式数据
const loading = ref(false)
const showClearModal = ref(false)

// 监听 flash 消息
watch(() => page.props.flash, (flash) => {
  if (flash?.success) {
    showNotification(flash.success, 'success')
  }
  if (flash?.error) {
    showNotification(flash.error, 'error')
  }
}, { immediate: true })

// 定时刷新
let refreshInterval = null

// 获取队列数据 - 使用 Inertia.js 推荐方式
const fetchQueueData = () => {
  router.reload({
    only: ['stats', 'recentJobs', 'failedJobs', 'queueHealth'],
    onStart: () => loading.value = true,
    onFinish: () => loading.value = false,
    onError: (errors) => {
      console.error('Failed to fetch queue data:', errors)
      showNotification('获取队列数据失败', 'error')
    }
  })
}

// 刷新数据
const refreshData = () => {
  fetchQueueData()
}

// 重试失败任务 - 使用 Inertia.js 推荐方式
const retryFailedJob = (jobId) => {
  if (!jobId) {
    showNotification('无效的任务ID', 'error')
    return
  }
  
  router.post(route('admin.queue.retry'), { job_id: jobId }, {
    preserveState: true,
    preserveScroll: true,
    onStart: () => loading.value = true,
    onFinish: () => loading.value = false
  })
}

// 重试所有失败任务 - 使用 Inertia.js 推荐方式
const retryAllFailedJobs = () => {
  router.post(route('admin.queue.retry'), {}, {
    preserveState: true,
    preserveScroll: true,
    onStart: () => loading.value = true,
    onFinish: () => loading.value = false
  })
}

// 删除失败任务 - 使用 Inertia.js 推荐方式
const deleteFailedJob = (jobId) => {
  if (!jobId) {
    showNotification('无效的任务ID', 'error')
    return
  }
  
  if (!confirm('确定要删除这个失败任务吗？')) return
  
  router.delete(route('admin.queue.delete-failed', jobId), {
    preserveState: true,
    preserveScroll: true,
    onStart: () => loading.value = true,
    onFinish: () => loading.value = false
  })
}

// 清空队列 - 使用 Inertia.js 推荐方式
const clearQueue = () => {
  router.post(route('admin.queue.clear'), { queue: 'default' }, {
    preserveState: true,
    preserveScroll: true,
    onStart: () => loading.value = true,
    onFinish: () => {
      loading.value = false
      showClearModal.value = false
    }
  })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  try {
    return new Date(dateString).toLocaleString('zh-CN')
  } catch (error) {
    console.error('Date formatting error:', error)
    return dateString
  }
}

// 组件挂载时开始定时刷新
onMounted(() => {
  // 初始化数据
  fetchQueueData()
  // 每30秒刷新一次
  refreshInterval = setInterval(fetchQueueData, 30000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>
